package com.yzyz.service.impl;

import java.util.List;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yzyz.bean.news.NewsBean;
import com.yzyz.bean.scenic.PictureBean;
import com.yzyz.dao.NewsDao;
import com.yzyz.service.NewsService;
import com.yzyz.utils.error.Error;

/**
 * 
 * @author David Sun
 * @Date   2010-4-20
 *
 */
@Transactional
public class NewsServiceImpl implements NewsService {

	private NewsDao newsDao;
	@Override
	public List<NewsBean> init(int topN) {
		List<NewsBean> list = this.newsDao.initTopN(topN);
		if(list == null){
			return null;
		}
		for(NewsBean news: list){
			news.setPictures(this.newsDao.getAllByNews(news.getId()));
		}
		return list;
	}

	@Override
	public List<NewsBean> paginate(int start, int limit) {
		if(start < 0){
			start = 0;
		}
		if(limit < 0){
			limit = 15;
		}
		return this.newsDao.paginate(start, limit);
	}

	@Override
	public void setNewsDao(NewsDao newsDao) {
		this.newsDao = newsDao;

	}
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public int add(Object object) {
		((NewsBean)object).setId(this.newsDao.save(object));
		return Error.SUCCESS;
	}
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public int delete(int id) {
		this.newsDao.delete(id);
		return Error.SUCCESS;
	}

	@Override
	public Object find(int id) {
		
		return this.newsDao.get(id);
	}
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public int update(Object object) {
		this.newsDao.update(object);
		return Error.SUCCESS;
	}

	@Override
	public int getCount() {
		
		return this.newsDao.getCount(-1);
	}
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public int addPicture(PictureBean picture) {
		this.newsDao.savePicture(picture);
		return Error.SUCCESS;
	}

	@Override
	public PictureBean findPicture(int newsId) {
		
		List<PictureBean> list = this.newsDao.getAllByNews(newsId);
		if(list == null || list.size() == 0){
			return null;
		}
		return list.get(0);
	}
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public void deletePicture(int newsId) {
		this.newsDao.deletePicture(newsId);
		
	}

}
